<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ProductVariant;
use App\Models\VariantAttributeValue;
use Illuminate\Http\Request;

class AdminVariantController extends Controller
{
    /**
     * 显示变体详情
     */
    public function show(ProductVariant $variant)
    {
        return response()->json($variant->load(['attributeValues.attribute']));
    }

    /**
     * 更新变体信息
     */
    public function update(Request $request, ProductVariant $variant)
    {
        $request->validate([
            'price' => 'required|numeric|min:0',
            'compare_price' => 'nullable|numeric|min:0',
            'stock_quantity' => 'required|integer|min:0',
        ]);

        // 更新变体基本信息
        $variant->update([
            'price' => $request->price,
            'compare_price' => $request->compare_price,
            'stock_quantity' => $request->stock_quantity,
        ]);

        // 对于 Inertia.js 请求，返回重定向
        return redirect()->back()
            ->with('success', '规格型号信息更新成功！');
    }

    /**
     * 切换变体状态
     */
    public function toggleStatus(ProductVariant $variant)
    {
        $variant->update([
            'is_active' => !$variant->is_active,
        ]);

        return redirect()->back()
            ->with('success', '变体状态更新成功！');
    }

    /**
     * 删除变体
     */
    public function destroy(ProductVariant $variant)
    {
        // 检查是否有关联的订单项
        if ($variant->orderItems()->exists()) {
            return redirect()->back()
                ->with('error', '该变体有关联的订单，无法删除！');
        }

        $variant->delete();

        return redirect()->back()
            ->with('success', '变体删除成功！');
    }
}
